package com.example.hyclipboard;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hyclipboard.view.MarqueeTextView;
import com.google.gson.Gson;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
	private final String SERVER_ADDRESS = "101.43.89.220";
	private final int SERVER_PORT = 28001;
	private static final String TAG = "HOYIN_MainActivity";
	private final String DATASTORE_TAG_UID = "uid";
	private final String DATASTORE_TAG_NICKNAME = "nickname";
	private final String DATASTORE_TAG_ACCOUNT = "account";

	private LinearLayout llMainBox;
	private FrameLayout flLoginBox;
	private View fl_header;
	private int[] loginBoxHeight;
	private EditText et_username;
	private EditText et_clipboard;

	private void push() {
		@SuppressLint("HandlerLeak")
		Handler handler = new Handler() {
			@Override
			public void handleMessage(@NonNull Message msg) {
				super.handleMessage(msg);
				if (msg.what == HttpClient.CONN_FAILED || msg.obj.equals("")) {
//					Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
					return;
				}
				Log.e(TAG, String.valueOf(msg.obj));
				Gson gson = new Gson();
				HttpClient.PushResponse resp;
				try {
					resp = gson.fromJson(String.valueOf(msg.obj), HttpClient.PushResponse.class);
				} catch (com.google.gson.JsonSyntaxException e) {
					e.printStackTrace();
					Toast.makeText(MainActivity.this, "服务器返回数据错误，试试Query一下看看是否成功", Toast.LENGTH_SHORT).show();
					return;
				}
				if (resp.status.equals(Macros.STATUS.FAILED)) {
					Toast.makeText(MainActivity.this, "上传失败，原因是: " + resp.reason, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
					query();
					et_clipboard.setText("");
				}
			}
		};
		HttpClient client = new HttpClient(SERVER_ADDRESS, SERVER_PORT, handler);
		TextView tv_clipboard = findViewById(R.id.et_main_clipboard);
		String content = String.valueOf(tv_clipboard.getText());
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		@SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss +08:00");
		String deviceName;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
			deviceName = Settings.Global.getString(this.getContentResolver(), Settings.Global.DEVICE_NAME);
		} else {
			deviceName = "Android Device";
		}
		String data = HttpClient.generatePushRequestBody(DataStore.loadData(this, DATASTORE_TAG_UID), df.format(timestamp), content, deviceName);
		client.send(data);

	}

	private void read(String cid) {
		@SuppressLint("HandlerLeak")
		Handler handler = new Handler() {
			@Override
			public void handleMessage(@NonNull Message msg) {
				super.handleMessage(msg);
				if (msg.what == HttpClient.CONN_FAILED || msg.obj.equals("")) {
					Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
				}
				Log.e(TAG, String.valueOf(msg.obj));
				Gson gson = new Gson();
				HttpClient.ReadResponse resp;
				try {
					resp = gson.fromJson(String.valueOf(msg.obj), HttpClient.ReadResponse.class);
					if (resp == null) {
						resp = new HttpClient.ReadResponse();
					}
				} catch (com.google.gson.JsonSyntaxException e) {
					e.printStackTrace();
					Toast.makeText(MainActivity.this, "服务器返回数据错误", Toast.LENGTH_SHORT).show();
				}
			}
		};
		HttpClient client = new HttpClient(SERVER_ADDRESS, SERVER_PORT, handler);
		String data = HttpClient.generateReadRequestBody(cid);
		client.send(data);
	}

	private void query() {
		@SuppressLint("HandlerLeak")
		Handler handler = new android.os.Handler(){
			@Override
			public void handleMessage(@NonNull Message msg) {
				super.handleMessage(msg);
				ArrayList<DatabaseDao.MemoData> memoDataList = new ArrayList<>();
				DatabaseDao dao = new DatabaseDao(MainActivity.this);
				if (msg.what == HttpClient.CONN_FAILED || msg.obj.equals("")) {
					Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
					memoDataList = dao.queryContent();
				}
				Log.e(TAG, String.valueOf(msg.obj));
				Gson gson = new Gson();
				HttpClient.QueryResponse resp;
				try {
					resp = gson.fromJson(String.valueOf(msg.obj), HttpClient.QueryResponse.class);
					if (resp == null) {
						resp = new HttpClient.QueryResponse();
					}
				} catch (com.google.gson.JsonSyntaxException e) {
					e.printStackTrace();
					Toast.makeText(MainActivity.this, "服务器返回数据错误，请重试", Toast.LENGTH_SHORT).show();
					return;
				}
				if (resp.status.equals(Macros.STATUS.FAILED)) {
					if (resp.reason == null) {
						Toast.makeText(MainActivity.this, "更新失败，唔知点解" + resp.reason, Toast.LENGTH_SHORT).show();
						return;
					}
					else if (!resp.reason.equals("")) {
						Toast.makeText(MainActivity.this, "更新失败，原因是：" + resp.reason, Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(MainActivity.this, "更新失败，唔知点解" + resp.reason, Toast.LENGTH_SHORT).show();
					}
					memoDataList = dao.queryContent();
				} else {
					for (int i = 0; i < resp.items.size(); i++) {
						DatabaseDao.MemoData memoData = new DatabaseDao.MemoData();
						HttpClient.MemoData respMemoData = resp.items.get(i);
						memoData.cid = respMemoData.cid;
						memoData.read = respMemoData.read?1:0;
						memoData.content = respMemoData.content;
						memoDataList.add(memoData);
						dao.insertContent(memoData);
					}
//					Toast.makeText(MainActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
				}

				RecyclerView rcv_clipboardContent = findViewById(R.id.rcv_main_content);
				LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);

				CBAdapter cbAdapter = new CBAdapter();

				ArrayList<DatabaseDao.MemoData> finalMemoDataList = memoDataList;
				cbAdapter.setOnItemClickListener(new CBAdapter.OnItemClickListener() {
					@Override
					public void onItemClick(int position, View itemView) {
						CBAdapter.selectedIndex = position;
						if (finalMemoDataList.get(position).read == 1) return;
						read(finalMemoDataList.get(position).cid);
						itemView.postDelayed(new Runnable() {
							@Override
							public void run() {
								query();
							}
						}, 500);
					}

					@Override
					public void onItemCopyClick(int position, View itemView) {
						CBAdapter.selectedIndex = position;

						String cid = finalMemoDataList.get(position).cid;
						fetch(cid);
						if (finalMemoDataList.get(position).read == 1) return;
						itemView.postDelayed(new Runnable() {
							@Override
							public void run() {
								read(cid);
							}
						}, 500);
						itemView.postDelayed(new Runnable() {
							@Override
							public void run() {
								query();
							}
						}, 1000);
					}
				});
				if (memoDataList.isEmpty()) {
					String content = "还没有剪贴板记录~";
					DatabaseDao.MemoData tempMemoData = new DatabaseDao.MemoData();
					tempMemoData.content = content;
					memoDataList.add(tempMemoData);
					cbAdapter.setOnItemClickListener(new CBAdapter.OnItemClickListener() {
						@Override
						public void onItemClick(int position, View view) {

						}

						@Override
						public void onItemCopyClick(int position, View view) {

						}
					});
				}
				cbAdapter.setData(memoDataList);
				rcv_clipboardContent.setLayoutManager(layoutManager);
				layoutManager.setOrientation(RecyclerView.VERTICAL);
				rcv_clipboardContent.setAdapter(cbAdapter);
				rcv_clipboardContent.setItemAnimator(new DefaultItemAnimator());
			}
		};
		if (DataStore.loadData(this, DATASTORE_TAG_UID).equals("")) {
			Toast.makeText(this, "请登录", Toast.LENGTH_SHORT).show();
			Handler handler1 = new Handler();
			handler1.postDelayed(new Runnable() {
				@Override
				public void run() {
					loginBoxShow(llMainBox, flLoginBox, 500);
					fl_header.setTag(R.id.isLoginBoxShow, true);
				}
			}, 500);
		} else {
			HttpClient client = new HttpClient(SERVER_ADDRESS, SERVER_PORT, handler);
			String deviceName;
			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
				deviceName = Settings.Global.getString(this.getContentResolver(), Settings.Global.DEVICE_NAME);
			} else {
				deviceName = "Android Device";
			}
			String data = HttpClient.generateQueryRequestBody(DataStore.loadData(this, DATASTORE_TAG_UID), deviceName);
			client.send(data);
		}
	}

	private void fetch(String cid) {
		@SuppressLint("HandlerLeak")
		Handler handler = new android.os.Handler(){
			@Override
			public void handleMessage(@NonNull Message msg) {
				super.handleMessage(msg);
				if (msg.what == HttpClient.CONN_FAILED || msg.obj.equals("")) {
					Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
				}
				Log.e(TAG, String.valueOf(msg.obj));
				Gson gson = new Gson();
				HttpClient.FetchResponse resp;
				try {
					resp = gson.fromJson(String.valueOf(msg.obj), HttpClient.FetchResponse.class);
					if (resp == null) {
						resp = new HttpClient.FetchResponse();
					}
				} catch (com.google.gson.JsonSyntaxException e) {
					e.printStackTrace();
					Toast.makeText(MainActivity.this, "服务器返回数据错误，请重试", Toast.LENGTH_SHORT).show();
					return;
				}
				if (resp.status.equals(Macros.STATUS.FAILED)) {
					if (!resp.reason.equals("")) {
						Toast.makeText(MainActivity.this, "获取失败，原因是：" + resp.reason, Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(MainActivity.this, "获取失败，唔知点解" + resp.reason, Toast.LENGTH_SHORT).show();
					}
				} else {
					ClipboardManager clipboardManager = (ClipboardManager) MainActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
					ClipData clipData = ClipData.newPlainText(null, resp.content);
					clipboardManager.setPrimaryClip(clipData);
					Toast.makeText(MainActivity.this, "已复制到剪贴板", Toast.LENGTH_SHORT).show();
				}
			}
		};
		HttpClient client = new HttpClient(SERVER_ADDRESS, SERVER_PORT, handler);
		String data = HttpClient.generateFetchRequestBody(cid);
		client.send(data);
	}

	private void login(String account, String password) {
		@SuppressLint("HandlerLeak")
		Handler handler = new Handler() {
			@SuppressLint("UseCompatLoadingForDrawables")
			@Override
			public void handleMessage(@NonNull Message msg) {
				super.handleMessage(msg);
				if (msg.what == HttpClient.CONN_FAILED || msg.obj.equals("")) {
					Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
					return;
				}
				Log.e(TAG, String.valueOf(msg.obj));
				Gson gson = new Gson();
				HttpClient.LoginResponse resp;
				try {
					resp = gson.fromJson(String.valueOf(msg.obj), HttpClient.LoginResponse.class);
					if (resp == null) {
						resp = new HttpClient.LoginResponse();
					}
				} catch (com.google.gson.JsonSyntaxException e) {
					e.printStackTrace();
					Toast.makeText(MainActivity.this, "服务器返回数据错误，请重试", Toast.LENGTH_SHORT).show();
					return;
				}
				if (resp.status.equals(Macros.STATUS.FAILED)) {
					if (!resp.reason.equals("")) {
						Toast.makeText(MainActivity.this, "登录失败，原因是：" + resp.reason, Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(MainActivity.this, "登录失败，唔知点解", Toast.LENGTH_SHORT).show();
					}
					return;
				} else {
					DataStore.saveData(MainActivity.this, DATASTORE_TAG_UID, resp.uid);
					DataStore.saveData(MainActivity.this, DATASTORE_TAG_NICKNAME, resp.nickname);
					DataStore.saveData(MainActivity.this, DATASTORE_TAG_ACCOUNT, resp.account);
					Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
					MainActivity.this.runOnUiThread(() -> {
						DatabaseDao dao = new DatabaseDao(MainActivity.this);
						dao.deleteAllContent();
						query();
						View fl_header = findViewById(R.id.fl_main_header);
						View llMainBox = findViewById(R.id.ll_main_mainContainer);
						FrameLayout flLoginBox = findViewById(R.id.fl_main_loginContainer);
						EditText acc = findViewById(R.id.et_main_loginAcc);
						EditText pwd = findViewById(R.id.et_main_loginPwd);
						EditText nik = findViewById(R.id.et_main_username);
						acc.setText("");
						pwd.setText("");
						fl_header.setTag(R.id.isLoginBoxShow, false);
						loginBoxDismiss(llMainBox, flLoginBox, 500);
						nik.setText(DataStore.loadData(MainActivity.this, DATASTORE_TAG_NICKNAME));
						nik.setBackground(getDrawable(R.drawable.ic_nickname_transparent));
						nik.setEnabled(false);
					});
				}
			}
		};
		HttpClient client = new HttpClient(SERVER_ADDRESS, SERVER_PORT, handler);
		String passwordMD5 = MD5.md5(account + password);
		String data = HttpClient.generateLoginRequestBody(account, passwordMD5);
		client.send(data);
	}

	private void signup(String account, String password, String username) {
		@SuppressLint("HandlerLeak")
		Handler handler = new Handler() {
			@Override
			public void handleMessage(@NonNull Message msg) {
				super.handleMessage(msg);
				if (msg.what == HttpClient.CONN_FAILED || msg.obj.equals("")) {
					Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
					return;
				}
				Log.e(TAG, String.valueOf(msg.obj));
				Gson gson = new Gson();
				HttpClient.SignUpResponse resp;
				try {
					resp = gson.fromJson(String.valueOf(msg.obj), HttpClient.SignUpResponse.class);
					if (resp == null) {
						resp = new HttpClient.SignUpResponse();
					}
				} catch (com.google.gson.JsonSyntaxException e) {
					e.printStackTrace();
					Toast.makeText(MainActivity.this, "服务器返回数据错误，请重试", Toast.LENGTH_SHORT).show();
					return;
				}
				if (resp.status.equals(Macros.STATUS.FAILED)) {
					if (!resp.reason.equals("")) {
						Toast.makeText(MainActivity.this, "注册失败，原因是：" + resp.reason, Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(MainActivity.this, "注册失败，唔知点解", Toast.LENGTH_SHORT).show();
					}
					return;
				} else {
					Toast.makeText(MainActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
					MainActivity.this.runOnUiThread(() -> {
						login(account, password);
					});
				}
			}
		};
		HttpClient client = new HttpClient(SERVER_ADDRESS, SERVER_PORT, handler);
		String passwordMD5 = MD5.md5(account + password);
		String data = HttpClient.generateSignUpRequestBody(username, account, passwordMD5);
		client.send(data);
	}

	@SuppressLint("UseCompatLoadingForDrawables")
	private void loginBoxDismiss(View mainBox, View loginBox, int duration) {
		int loginBoxHeight = loginBox.getHeight();
		et_username.setHint("未登录");
		et_username.setText(DataStore.loadData(this, DATASTORE_TAG_NICKNAME));
		et_username.setBackground(getDrawable(R.drawable.ic_nickname_transparent));
		et_username.setEnabled(false);
		ObjectAnimator loginBoxAnimator = ObjectAnimator.ofFloat(loginBox, "translationY", 0, -loginBoxHeight);
		ObjectAnimator mainBoxAnimator = ObjectAnimator.ofFloat(mainBox, "translationY", loginBoxHeight, 0);
		loginBoxAnimator.setDuration(duration);
		mainBoxAnimator.setDuration(duration);
		loginBoxAnimator.start();
		mainBoxAnimator.start();
	}

	@SuppressLint("UseCompatLoadingForDrawables")
	private void loginBoxShow(View mainBox, View loginBox, int duration) {
		int loginBoxHeight = loginBox.getHeight();
		et_username.setHint("昵称");
		et_username.setText("");
		et_username.setBackground(getDrawable(R.drawable.ic_nickname));
		et_username.setEnabled(true);
		ObjectAnimator loginBoxAnimator = ObjectAnimator.ofFloat(loginBox, "translationY", -loginBoxHeight, 0);
		ObjectAnimator mainBoxAnimator = ObjectAnimator.ofFloat(mainBox, "translationY", 0, loginBoxHeight);
		loginBoxAnimator.setDuration(duration);
		mainBoxAnimator.setDuration(duration);
		loginBoxAnimator.start();
		mainBoxAnimator.start();
	}

	@SuppressLint("UseCompatLoadingForDrawables")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
//		hideStatusBar();

//      禁用深色模式
		AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

		View btn_query = findViewById(R.id.btn_main_refresh);
		View btn_push = findViewById(R.id.btn_main_upload);
		fl_header = findViewById(R.id.fl_main_header);
		llMainBox = findViewById(R.id.ll_main_mainContainer);
		flLoginBox = findViewById(R.id.fl_main_loginContainer);
		et_username = findViewById(R.id.et_main_username);
		et_clipboard = findViewById(R.id.et_main_clipboard);

		et_clipboard.setOnClickListener(view -> {
			et_clipboard.clearFocus();
			et_clipboard.postDelayed(new Runnable() {
				@Override
				public void run() {
					et_clipboard.requestFocus();
					InputMethodManager manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
					if (manager != null) manager.showSoftInput(et_clipboard, 0);
				}
			}, 0);
		});

		flLoginBox.post(() -> {
			flLoginBox.setVisibility(View.VISIBLE);
			loginBoxDismiss(llMainBox, flLoginBox, 0);
		});

		fl_header.setTag(R.id.isLoginBoxShow, false);
		fl_header.setOnClickListener(view -> {
			if (!(boolean) fl_header.getTag(R.id.isLoginBoxShow)) {
				loginBoxShow(llMainBox, flLoginBox, 500);
				fl_header.setTag(R.id.isLoginBoxShow, true);

			} else {
				loginBoxDismiss(llMainBox, flLoginBox, 500);
				fl_header.setTag(R.id.isLoginBoxShow, false);

			}
		});
		btn_query.setOnClickListener(view -> {
			query();
		});
		btn_push.setOnClickListener(view -> {
			et_clipboard = findViewById(R.id.et_main_clipboard);
			if (String.valueOf(et_clipboard.getText()).equals("")) {
				Toast.makeText(this, "未输入内容", Toast.LENGTH_SHORT).show();
			} else {
				push();
			}
		});
		query();

		View v_accContainer = findViewById(R.id.ll_main_acc);
		View v_pwdContainer = findViewById(R.id.ll_main_pwd);
		EditText et_acc = findViewById(R.id.et_main_loginAcc);
		EditText et_pwd = findViewById(R.id.et_main_loginPwd);
		et_acc.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@SuppressLint("UseCompatLoadingForDrawables")
			@Override
			public void onFocusChange(View view, boolean b) {
				if (b) {
					v_accContainer.setBackground(getDrawable(R.drawable.vector_drawable_acc2));
				} else {
					v_accContainer.setBackground(getDrawable(R.drawable.vector_drawable_acc1));
				}
			}
		});
		et_pwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@SuppressLint("UseCompatLoadingForDrawables")
			@Override
			public void onFocusChange(View view, boolean b) {
				if (b) {
					v_pwdContainer.setBackground(getDrawable(R.drawable.vector_drawable_pwd2));
				} else {
					v_pwdContainer.setBackground(getDrawable(R.drawable.vector_drawable_pwd1));
				}
			}
		});

		View btn_login = findViewById(R.id.btn_main_login);
		View btn_signup = findViewById(R.id.btn_main_signup);
		btn_login.setOnClickListener(view -> {
			String acc = String.valueOf(et_acc.getText());
			String pwd = String.valueOf(et_pwd.getText());
			if (acc.equals("") || pwd.equals("")) {
				Toast.makeText(this, "请输入账号密码", Toast.LENGTH_SHORT).show();
			} else if (!FormChecker.isOnlyLetterAndNumber(acc)) {
				Toast.makeText(this, "账号不存在", Toast.LENGTH_SHORT).show();
			} else {
				login(acc, pwd);
			}
		});
		btn_signup.setOnClickListener(view -> {
			String acc = String.valueOf(et_acc.getText());
			String pwd = String.valueOf(et_pwd.getText());
			String nik = String.valueOf(et_username.getText());
			if (acc.equals("") || pwd.equals("")) {
				Toast.makeText(this, "请输入账号密码", Toast.LENGTH_SHORT).show();
			} else if (nik.equals("")) {
				Toast.makeText(this, "请输入一个昵称", Toast.LENGTH_SHORT).show();
			} else {
				if (!(acc.length() >= 10 && acc.length() <= 18) || !(pwd.length() >= 10 && pwd.length() <= 18)) {
					Toast.makeText(this, "账号密码长度要求在 10 ~ 18 位之间", Toast.LENGTH_SHORT).show();
				} else if (!FormChecker.isOnlyLetterAndNumber(acc)) {
					Toast.makeText(this, "账号只能包含数字和字母", Toast.LENGTH_SHORT).show();
				} else {
					signup(acc, pwd, nik);
				}
			}
		});

		et_username.setText(DataStore.loadData(MainActivity.this, DATASTORE_TAG_NICKNAME));

		ClipboardManager clipboardManager = (ClipboardManager) MainActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
		ClipData clipData = clipboardManager.getPrimaryClip();
		if (null != clipData && clipData.getItemCount() > 0) {
			// 从数据集中获取（粘贴）第一条文本数据
			ClipData.Item item = clipData.getItemAt(0);
			if (null != item) {
				String content = item.getText().toString();
				EditText et_clipboard = findViewById(R.id.et_main_clipboard);
				et_clipboard.setText(content);
			}
		}
	}

	private void hideStatusBarNavigationBar() {
		Window window = getWindow();
		window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
		window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
		window.setStatusBarColor(Color.TRANSPARENT);
		window.setNavigationBarColor(Color.TRANSPARENT);
	}

	private void hideStatusBar() {
		Window window = getWindow();
		window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
		window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
		window.setStatusBarColor(Color.TRANSPARENT);
	}

	private static class CBAdapter extends RecyclerView.Adapter<CBAdapter.VH> {
		public static int selectedIndex = -1;
		private List<DatabaseDao.MemoData> mData;
		private OnItemClickListener onItemClickListener;

		public void setData(ArrayList<DatabaseDao.MemoData> data) {
			this.mData = data;
		}

		@NonNull
		@Override
		public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
			View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.paste_content_item, parent, false);
			return new VH(view);
//			return holder;
		}

		@SuppressLint({"UseCompatLoadingForDrawables", "NotifyDataSetChanged"})
		@Override
		public void onBindViewHolder(@NonNull VH holder, int position) {
			holder.textView.setText(mData.get(position).content);

			if (selectedIndex != -1 && selectedIndex < mData.size()) {
				if (selectedIndex == position) {
					holder.textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
				} else {
					holder.textView.setEllipsize(TextUtils.TruncateAt.END);
				}
			}
			if (mData.get(position).read == 0) {
				holder.container.setBackground(holder.container.getResources().getDrawable(R.drawable.ic_item1_bg));
			} else {
				holder.container.setBackground(holder.container.getResources().getDrawable(R.drawable.ic_item2_bg));
			}
			holder.copyButton.setOnClickListener(view -> {
				onItemClickListener.onItemCopyClick(position, holder.itemView);
				notifyDataSetChanged();
			});
			holder.container.setOnClickListener(view -> {
				onItemClickListener.onItemClick(position, holder.itemView);
				notifyDataSetChanged();
			});
		}

		public interface OnItemClickListener {
			void onItemClick(int position, View view);
			void onItemCopyClick(int position, View view);
		}

		public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
			this.onItemClickListener = onItemClickListener;
		}

		@Override
		public int getItemCount() {
			return mData.size();
		}

		static class VH extends RecyclerView.ViewHolder {
			public final MarqueeTextView textView;
			public final View copyButton;
			public final LinearLayout container;
			public VH(@NonNull View itemView) {
				super(itemView);
				container = itemView.findViewById(R.id.ll_pci_item);
				textView = itemView.findViewById(R.id.tv_pci_text);
				copyButton = itemView.findViewById(R.id.btn_pci_copy);
			}
		}
	}
}